package org.wujiangbo.thread;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.wujiangbo.domain.user.User;
import org.wujiangbo.mapper.user.UserMapper;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * <p>向数据库中添加数据的线程</p>
 * @author 波波老师(微信 ： javabobo0513)
 */
@Slf4j
public class InsertUserThread implements Runnable{

    private List<User> userList;
    private CountDownLatch latch;
    private UserMapper userMapper;
    private SqlSession session;

    public InsertUserThread(List<User> userList, CountDownLatch latch, UserMapper userMapper, SqlSession session){
        this.userList = userList;
        this.latch = latch;
        this.userMapper = userMapper;
        this.session = session;
    }

    @Override
    public void run() {
        //获取测试用户集合数据
        int commitCount = 5000;//每次提交的数量条数
        long startTime = System.currentTimeMillis();
        for(int i=0; i<userList.size(); i++){
            userMapper.insert(userList.get(i));
            if (i != 0 && i % commitCount == 0) {
                session.commit();
            }
        }
        session.commit();
        session.clearCache();
        session.close();
        long endTime = System.currentTimeMillis();
        log.info("线程：{}-执行完毕，耗时：{}毫秒", Thread.currentThread().getName(), (endTime - startTime));
        latch.countDown();
    }
}